package com.harmontronics.hanma.paas.paas.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.harmontronics.hanma.paas.paas.annotation.Log;
import com.harmontronics.hanma.paas.paas.common.ResponseEntity;
import com.harmontronics.hanma.paas.paas.common.PageBase;
import cn.hutool.core.convert.Convert;
import com.harmontronics.hanma.paas.paas.consts.BaseI18nKeyEnum;
import com.harmontronics.hanma.paas.paas.consts.FileTypeConstants;
import com.harmontronics.hanma.paas.paas.dto.input.ScriptExecutionInput;
import com.harmontronics.hanma.paas.paas.exception.ErrorKeyException;
import com.harmontronics.hanma.paas.paas.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.harmontronics.hanma.paas.paas.service.HmScriptAppService;
import com.harmontronics.hanma.paas.paas.dto.output.HmScriptResult;
import com.harmontronics.hanma.paas.paas.dto.input.HmScriptCreateInput;
import com.harmontronics.hanma.paas.paas.dto.input.HmScriptUpdateInput;
import com.harmontronics.hanma.paas.paas.domain.app.entity.HmScript;
import com.harmontronics.hanma.paas.paas.utils.ParamUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;


/**
 * 脚本
 *
 * @author paas-generator
 * @email paas-generator@harmontronics.com
 * @date 2021-04-19 14:08:22
 */
@RestController
@RequestMapping("/api/hm-script")
@Api(tags = {"脚本"})
public class HmScriptController {
    @Autowired
    private HmScriptAppService hmScriptappService;

    /**
     * 列表
     */
    @GetMapping("/list")
    @ApiOperation("列表")
    public ResponseEntity<List<HmScriptResult>> list() {
        List<HmScript> hmScriptList = hmScriptappService.getList();

        return ResponseEntity.ok(Convert.toList(HmScriptResult.class, hmScriptList));
    }

    /**
     * 分页列表
     */
    @GetMapping("/page/list")
    @ApiOperation("分页列表")
    public ResponseEntity<PageBase<HmScriptResult>> list(
            @ApiParam(value = "编码") @RequestParam(required = false) String code,
            @ApiParam(value = "名称") @RequestParam(required = false) String name,
            @ApiParam(value = "页码", defaultValue = "1") @RequestParam(required = false, defaultValue = "1") int pageNo,
            @ApiParam(value = "每页数据条数", defaultValue = "20") @RequestParam(required = false, defaultValue = "20") int pageSize) {
        PageBase<HmScript> hmScriptPageBase = hmScriptappService.getList(name, code, pageNo, pageSize);
        PageBase<HmScriptResult> resultPageBase = PageBase.copy(hmScriptPageBase, HmScriptResult.class);
        return ResponseEntity.ok(resultPageBase);
    }


    /**
     * 信息
     */
    @GetMapping("/info")
    @ApiOperation("详情")
    public ResponseEntity<HmScriptResult> info(@RequestParam Long id) {
        HmScript hmScript = hmScriptappService.findById(id);
        HmScriptResult result = BeanUtil.toBean(hmScript, HmScriptResult.class);
        return ResponseEntity.ok(result);
    }

    /**
     * 保存
     */
    @PostMapping()
    @ApiOperation("保存")
    @Log("新增了脚本")
    public ResponseEntity<String> save(@Valid @RequestBody HmScriptCreateInput hmScriptInput, BindingResult bindingResult) {
        ParamUtils.valid(bindingResult);
        HmScript hmScript = BeanUtil.toBean(hmScriptInput, HmScript.class);
        hmScriptappService.save(hmScript);

        return ResponseEntity.ok();
    }

    /**
     * 修改
     */
    @PutMapping
    @ApiOperation("修改")
    @Log("修改了脚本")
    public ResponseEntity<String> update(@Valid @RequestBody HmScriptUpdateInput hmScriptInput, BindingResult bindingResult) {
        ParamUtils.valid(bindingResult);
        HmScript hmScript = BeanUtil.toBean(hmScriptInput, HmScript.class);
        hmScriptappService.update(hmScript);
        return ResponseEntity.ok();
    }

    /**
     * 删除
     */
    @DeleteMapping()
    @ApiOperation("删除")
    @Log("删除了脚本")
    public ResponseEntity<String> delete(@RequestBody Long[] ids) {
        hmScriptappService.remove(Arrays.asList(ids));

        return ResponseEntity.ok();
    }


    @PostMapping("execute")
    @ApiOperation("执行脚本")
    public ResponseEntity<?> execute(@RequestBody ScriptExecutionInput executionInput) throws IOException {
        Object object = hmScriptappService.execute(executionInput.getScriptCode(),executionInput.getValues());
        return ResponseEntity.ok(object);
    }


    @GetMapping("valid-field")
    @ApiOperation("字段重复检查")
    public ResponseEntity<String> validField(@RequestParam String key, @RequestParam String value, @RequestParam(required = false) Long id) {
        hmScriptappService.validField(id, key, value);
        return ResponseEntity.ok();
    }

    @PostMapping("/upload")
    @ApiOperation("上传脚本")
    @Log("上传了脚本文件")
    public ResponseEntity<String> singleScriptUpload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new ErrorKeyException(BaseI18nKeyEnum.REQUEST_PARAM_ERROR);
        }
        Long fileSize = file.getSize();
        Boolean result = FileUtil.checkFileSize(fileSize, 10, "M");
        if (!result) {
            throw new ErrorKeyException(BaseI18nKeyEnum.FILESIZE_LONG);
        }
        String originalFileName = file.getOriginalFilename();
        int lastDotIndex = originalFileName.lastIndexOf(".");
        String fileType = originalFileName.substring(lastDotIndex + 1);
        if (!fileType.equalsIgnoreCase(FileTypeConstants.FILE_JS) && !fileType.equalsIgnoreCase(FileTypeConstants.FILE_GROOVY)) {
            throw new ErrorKeyException(BaseI18nKeyEnum.REQUEST_PARAM_ERROR);
        }

        String fileName = hmScriptappService.saveScriptFile(file.getBytes(), fileType);

        return ResponseEntity.ok(fileName);
    }

}
